<template>
  <div  class="main w-full mt-4 sm:mt-6 md:mt-8 mb-8 bg-light-100 p-2 sm:p-4 md:p-6 lg:p-8 bg-opacity-90  shadow-xl rounded-lg overflow-hidden">
    <ul 
        ref="topicItems"
        class="grid  grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2 md:gap-6 lg:gap-8 w-full"
        v-infinite-scroll="load"
        infinite-scroll-distance="10"
        :infinite-scroll-disabled="disabled"
        :infinite-scroll-immediate="true"
        v-if="isMounted" 
    >
      <TransitionGroup
        enter-active-class="animate__animated  animate__zoomIn animate__fast"
      >
        <li v-for="item in topicAnimation" :key="item._id"
        class="bg-light-100 border-1  hover:shadow-xl transition duration-400 ease-in-out rounded-lg overflow-hidden"
      >
        <!-- 图片 -->
        <div class="p-2 sm:p-4 border-b">
          <div class=" flex justify-center items-center">
            <el-image
              v-for="img,index in item.images.slice(0,1)" :key="img._id"
              class="px-1" style="width: 90%; max-height: 16rem; border-radius: 1rem;aspect-ratio: 2/3; " :src="IMG_URL_SERVER+img.url"
              :preview-src-list="item.images.slice(0,3).map((val:any)=> IMG_URL_SERVER+val.url)" :initial-index="index"
              :alt="img.name" fit="cover" >
            </el-image>
            <el-image v-if="item?.images?.length === 0" class="px-1" style="width: 90%; max-height: 16rem; border-radius: 1rem;aspect-ratio: 2/3;"></el-image>
          </div>
        </div>
        <div class="p-2 sm:p-4">
          <div class="min-h-8 leading-8 sm:min-h-12">
            <!-- 标题 -->
            <RouterLink :to="`/article/${item._id}`" class="h-full block">
              <div class="line-clamp-2  text-base md:text-xl leading-5 font-semibold hover:text-blue-500 title">{{item.title}}</div>
            </RouterLink>
          </div>
          
          <div class="flex items-center justify-between sm:mt-2">
            <div class="flex justify-start items-center truncate w-80%">
              <RouterLink :to="`/accountCenter/postList/${item?.user?._id}`">
                <div class="mr-2">
                  <img :src="IMG_URL_SERVER+item?.user?.avatar?.url" :alt="item?.user?.avatar?.name" class="avatar wh-6" />
                </div>
              </RouterLink>
              <RouterLink :to="`/accountCenter/postList/${item?.user?._id}`">
                <div><span class="hover:text-blue-500 text-sm md:text-base ">{{item?.user?.nickname}}</span></div>
              </RouterLink>
            </div>
            <div>
              <!-- 点赞 -->
              <template v-if="item.isVote">
                <div class="i-carbon-thumbs-up-filled cursor-pointer wh-6 opacity-80 bg-gradient-to-r from-blue-600 to-purple-500  "
                  @click="addLiking(item._id,$event)" :data-flag="item?.isVote"></div>
              </template>
              <template v-else>
                <div class="i-carbon-thumbs-up-filled wh-6 cursor-pointer opacity-50 " @click="addLiking(item._id,$event)"
                  :data-flag="item?.isVote"></div>
              </template>
            </div>
          </div>
        </div>
        
      
        </li>
      </TransitionGroup>
    </ul>

    <template v-if="topicList?.length === 0">
      <el-empty class="bg-light-100 min-h-140" description="暂时还没有贴子哦" />
    </template>
    <template v-else>
      <div v-if="loading" class="  h-20 mt-2 flex justify-center items-center">
        <div class="animate-spin mr-1 bg-blue-500 wh-8! i-carbon-restart "></div>
        <span class="text-2xl leading-20">
          加载中...
        </span>
      </div>
      <div v-if="noMore" class="">
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { fetchCateTopic, fetchLikingTopic, fetchUnLikingTopic } from "@/server"
import { IMG_URL_SERVER } from "@/config"



//router
const route = useRoute()
//帖子列表
const topicList: any = ref([])
//帖子动画
const topicAnimation: any = ref([])
//登录用户Store
const authStore = useAuthStore()
//utilsStore
const utilsStore = useUtilsStore()
//reload 重载
const { reloadFlag } = inject<any>('reload')
//刷新等待时间
const loadingTime = 600  

//解决v-infinite-scroll数据渲染报错
const isMounted = ref(false);

//加载更多
let start = 0 //动画开始
let PageStep: number = 8 //跳过
let nextPage = ref(PageStep) //结束索引
const loading = ref(false)
const noMore = computed(() => nextPage.value >= topicList.value?.length)
const disabled = computed(() => loading.value || noMore.value)    //禁用加载

function topicAnimationFn() {       //帖子动画函数
  let timer = setInterval(() => {
    if (start >= nextPage.value || start >= topicList.value.length) {
      loading.value = false
      clearInterval(timer)
      return
    }
    topicAnimation.value.push(topicList.value[start])
    start++
  }, 200)
}

const load = () => {        //加载函数
  loading.value = true
  setTimeout(() => {
    nextPage.value += PageStep
    topicAnimationFn()
  }, loadingTime)
}


//点击点赞
const addLiking = (id: any, e: any) => {
  //保护条款
  if (!authStore.isAuthenticated) {
    utilsStore.dialogTableVisible = true
    return false;
  }
  if (e.target.dataset?.flag === 'false') {
    fetchLikingTopic(id, () => {
      e.target.dataset.flag = 'true'
      e.target.classList.add("opacity-80", "bg-gradient-to-r", "from-blue-600", "to-purple-500")
      e.target.classList.remove("opacity-50")
      return true;
    })
  } else {
    fetchUnLikingTopic(id, () => {
      e.target.dataset.flag = 'false'
      e.target.classList.remove("opacity-80", "bg-gradient-to-r", "from-blue-600", "to-purple-500")
      e.target.classList.add("opacity-50")
      return true;
    })
  }
}



watchEffect(() => {
  if (reloadFlag.value || route.params.id) {
    fetchCateTopic("话题", () => true).then((data) => {
      console.log(data);
      topicList.value = data
      load()
    })
  }
})

const topicItems = ref()
console.log(topicItems);



onMounted(() => {
  isMounted.value = true;   //解决v-infinite-scroll数据渲染报错
  topicAnimationFn()        //帖子动画函数
})

</script>

<style scoped>
.main{
  min-height: calc(100vh - 15rem);
}
</style>

<route lang="yaml">
meta:
  layout: home
</route>
